define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            var distributor_type='';
            var distributor='';
            var province='全国';
            var audit_status='全部';
            var city='全部';
            var year='';
            var charge_person_admin_id='';
            var group_id=0
            var admin_id=0
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'issuer/distributor/index',
                    table: 'distributor',
                }
            });

            var table = $("#table");
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据

                // console.log(data);
                //这里我们手动设置底部的值
                $("#distributor_num").text(data.total);
           //     $("#now_income").text(data.now_income);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                search:false,
                sortOrder:'desc',
                showExport: false,
                pagination: false,
                columns: [
                    [
                      //  {checkbox: true},
                       // {field: 'id', title: __('Id')},
                        {field: 'distributor_name', title: '渠道名称', operate: false},
                        {field: 'distributor_type', title: __('渠道主体'),operate:false,formatter:function (value) {
                                if (value==1){
                                    return "<span style=''>大学</span>";
                                }else if(value==2){
                                    return "<span style=''>高中</span>";
                                }else if(value==3){
                                    return "<span style=''>中职</span>";
                                }else if(value==4){
                                    return "<span style=''>机构</span>";
                                }else if(value==5){
                                    return "<span style=''>个体</span>";
                                }else if(value==6){
                                    return "<span style=''>政府</span>";
                                }
                            }},
                        {field: 'new_address', title: '发行地区', operate: false},
                        {field: 'year', title: '合作年份', operate: false},
                        {field: 'price', title: '发行最低单价', operate: false},
                        {field: 'put_amount', title: '发行总额', operate: false},
                        {field: 'activate_num', title: '激活总数', operate: false},
                        {field: 'username', title: '手机账号', operate: false},
                        {field: 'createtime', title: '创建时间', formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true, visible: false},
                        {field: 'audit_status', title: __('审核状态'),operate:false,formatter:function (value) {
                                if (value==0){
                                    return "<span style=''>未审核</span>";
                                }else if(value==1){
                                    return "<span style=''>已审核</span>";
                                }else if(value==2){
                                    return "<span style=''>未通过</span>";
                                }
                            }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,buttons: [
                                {
                                    name: 'issue',
                                    text: '会员卡发行',
                                    classname: 'btn btn-success sublet_edit btn-xs btn-magic btn-dialog',
                                    url:"issuer/distributor/issue?ids={ids}",
                                },
                                {
                                    name: 'edit',
                                    text: '账号修改',
                                    classname: 'btn btn-success sublet_edit btn-xs btn-magic btn-dialog',
                                    url:"issuer/distributor/edit",
                                },
                                // {
                                //     name: 'audit',
                                //     text: '重新审核',
                                //     classname: 'btn btn-success sublet_edit btn-xs btn-magic btn-dialog',
                                //     url:"issuer/distributor/audit",
                                // },
                                {
                                    name: 'open',
                                    text: '开启账号',
                                    classname: 'btn btn-success sublet_edit btn-xs btn-magic btn-ajax',
                                    icon: 'fa fa-trash-o',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        // if (row.group_id==13){
                                        //     return false;
                                        // }else {
                                        //     return true;
                                        // }
                                        return true;
                                    },
                                    url: 'issuer/distributor/open',
                                    confirm: '确认开启账号?',
                                    success: function (data, ret) {
                                        Layer.alert('开启账号成功');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        location.reload();
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                                {
                                    name: 'close',
                                    text: '关闭账号',
                                    classname: 'btn btn-success sublet_edit btn-xs btn-magic btn-ajax',
                                    icon: 'fa fa-trash-o',
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    },
                                    url: 'issuer/distributor/close',
                                    confirm: '确认关闭账号?',
                                    success: function (data, ret) {
                                        Layer.alert('关闭账号成功');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        location.reload();
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ]
                            , formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                if(row.audit_status == 1){
                                    $(table).data("operate-issue", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                }else{
                                    $(table).data("operate-issue", null); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                }
                               // console.log(is_main);
                                $(table).data("operate-edit", null); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                $(table).data("operate-del", null); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }},
                    ]
                ],

            });
            $('#all').off().on('click',function(){
                $('.type-item').removeClass('type-active');
                $(this).addClass('type-active');
                audit_status = '全部';
                change_search();
            });

            $('#unapproved').off().on('click',function(){
                $('.type-item').removeClass('type-active');
                $(this).addClass('type-active');
                audit_status = 0;
                change_search();
            });

            $('#reviewed').off().on('click',function(){
                $('.type-item').removeClass('type-active');
                $(this).addClass('type-active');
                audit_status = 1;
                change_search();
            });
            $('#failed').unbind();
            $('#failed').off().on('click',function(){
                $('.type-item').removeClass('type-active');
                $(this).addClass('type-active');
                audit_status = 2;
                change_search();
            });
            // 为表格绑定事件
            $('.year').off().on('change',function(){
                year=$(this).val();
                console.log(year);
                change_search(1);
            });

            $('.charge_person').off().on('change',function(){
                charge_person_admin_id=$(this).val();
                change_search(1);
            });

            $('.search_distributor').off().on('click',function(){
                distributor=$('#distributor').val();
                change_search(2);
            });

            // $('#all').off().on('click',function(){
            //     $('.type-item').removeClass('type-active');
            //     $(this).addClass('type-active');
            //     change_search();
            // });

            function change_search(){
                console.log(province,'province');
                var opt = {
                    url: 'admin/distributor/index?year='+year+'&distributor_type='+distributor_type+'&distributor='+distributor
                        +'&province='+province+'&city='+city+'&audit_status='+audit_status+'&group_id='+group_id+'&admin_id='+admin_id,//这里可以包装你的参数
                };
                $('#table').bootstrapTable('refresh', opt);
            }

            $(document).on('click', '.distributor_add', function (row){ //创建渠道
                Fast.api.open('issuer.distributor/add', __("创建渠道"),{area:['80%', '80%']}, {
                    callback:function(value){

                    }
                });
            });

            var chat = new Vue({
                el: "#search",
                data() {
                    return {
                        channelList: ['全部列表','大学','高中','中职','机构','个体','政府'],
                        yearList: ['全部',2023,2024,2025],
                        currentChannel: 0,
                        regionOptions: [],
                        personOptions: [],
                        props: {value:'label'},
                        props2: {value:'id'},
                        province: '全国',
                        city: '全部',
                        date: '',
                        charge_person: [],
                        person: '',
                        year: ''
                    }
                },
                created() {
                    this.getRegion();
                    this.getPerson()
                    this.charge_person = Config.charge_person
                    console.log(this.charge_person,'this.charge_person');
                },
                methods: {
                    //获取地区信息
                    getRegion() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'admin/distributor/getProvinceCity',
                        }, function(data, ret) {
                            console.log(data.info,'data.info');
                            that.regionOptions = JSON.parse(data.info)
                            return false;
                        }, function(data, ret) {
                            //失败的回调
                            Toastr.error(ret.msg);
                            return false;
                        });
                    },
                    //获取发行人员信息
                    getPerson() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'admin/distributor/getGroupInfo',
                        }, function(data, ret) {
                            console.log(data.info,'data.info');
                            that.personOptions = JSON.parse(data.info)
                            return false;
                        }, function(data, ret) {
                            //失败的回调
                            Toastr.error(ret.msg);
                            return false;
                        });
                    },
                    //选择渠道主体
                    selectChannel(index) {
                        this.currentChannel = index
                        distributor_type = index
                        change_search()
                    },
                    //选择年份
                    changeYear(e) {
                        year = e
                        if(year == '全部') {
                            year = ''
                        }
                        change_search()
                    },
                    //选择发行人员
                    changePerson(e) {
                        console.log(e, 'e');
                        group_id = e
                        change_search()
                    },
                    //修改地区
                    handleChange(e) {
                        console.log(e, 'e');
                        province = e[0]
                        city = e[1]
                        change_search()
                    },
                }
            })
            // 为表格绑定事件
            Table.api.bindevent(table);
            Controller.api.bindevent();
        },
        add: function () {
            $(document).on("click", ".add_button", function () {
                var distributor_name = $('#distributor_name').val()?$('#distributor_name').val():'';
                var province_city = addform.value[1]?addform.value[1]:'';
                var distributor_type= $("input[name='distributor_type']:checked").val()?$("input[name='distributor_type']:checked").val():'';
                var year= $("input[name='year']:checked").val()?$("input[name='year']:checked").val():'';
                var price = $('#price').val()?$('#price').val():'';
                var username = $('#username').val()?$('#username').val():'';
                var address = $('#address').val()?$('#address').val():'';
                var invoice_title = $('#invoice_title').val()?$('#invoice_title').val():'';

                if(distributor_name=='' || province_city=='' || distributor_type=='' || year==''){
                    Toastr.error('选项不允许为空,请检查');
                    return false;
                }

                var data ={
                    'distributor_name':distributor_name,
                    'city_id':province_city,
                    'distributor_type':distributor_type,
                    'year':year,
                    'price':price,
                    'username':username,
                    'address':address,
                    'invoice_title':invoice_title
                };
                console.log(data);
                Fast.api.ajax({
                    url:'issuer/distributor/add',
                    data:data
                }, function(data, ret){
                    console.log(data);
                    Fast.api.close();
                    //成功的回调
                    return true;
                }, function(data, ret){
                    // console.log(data);
                    //失败的回调
                    Toastr.error(ret.msg);
                    return false;
                });
            });

            var addform = new Vue({
                el: "#add-form",
                data() {
                    return {
                        data: [],
                        options: [],
                        value: '',
                        searchKey: '',
                    }
                },
                created() {
                    this.getRegion();
                },
                methods: {
                    handleChange() {
                        console.log(111, '');
                    },
                    //获取地区信息
                    getRegion() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'issuer/distributor/getProvinceCity',
                        }, function(data, ret) {
                            console.log(data.info,'data.info');
                            that.options = JSON.parse(data.info)
                            return false;
                        }, function(data, ret) {
                            //失败的回调
                            Toastr.error(ret.msg);
                            return false;
                        });
                    },
                },
            })
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        issue: function () {
            $(document).on("click", ".add_button", function () {
                var province_city = addform.value[1]?addform.value[1]:'';
                var put_mode= $("input[name='put_mode']:checked").val()?$("input[name='put_mode']:checked").val():'';
                var year = $("input[name='year']:checked").val()?$("input[name='year']:checked").val():'';
                var put_num = $('#put_num').val()?$('#put_num').val():'';
                var put_type = $("input[name='put_type']:checked").val()?$("input[name='put_type']:checked").val():'';
                var put_price = $('#put_price').val()?$('#put_price').val():'';
                var put_image = $('#put_image').val()?$('#put_image').val():'';
                var guarantee_result = $('#guarantee_result').text()?$('#guarantee_result').text():'';
                var voucher =  $("input[name='voucher']:checked").val()?$("input[name='voucher']:checked").val():'';
                var send_result = $('#send_result').val()?$('#send_result').val():'';
                var brand_name = $('#brand_name').val()?$('#brand_name').val():'';
                var distributor_id = $('#distributor_id').val()?$('#distributor_id').val():'';
                var is_higher = $("input[name='is_higher']:checked").val()?$("input[name='is_higher']:checked").val():'';
                if(put_mode=='' || year=='' || put_num=='' || put_type=='' ){
                    Toastr.error('选项不允许为空,请检查');
                    return false;
                }
                if((voucher == 1 || voucher == 2) && put_image == ""){
                    Toastr.error('请上传凭证');
                    return false;
                }
                if(put_num ==  "" || put_num <= 0){
                    Toastr.error('发行张数不能小于0');
                    return false;
                }
                var data ={
                    'city_id':province_city,
                    'put_mode':put_mode,
                    'year':year,
                    'put_num':put_num,
                    'is_higher':is_higher,
                    'cooperation_status':voucher,
                    'guarantee_result':guarantee_result,
                    'put_image':put_image,
                    'put_type':put_type,
                    // 'put_image':put_image,
                    'put_price':put_price,
                    'send_result':send_result,
                    'brand_name':brand_name,
                    'distributor_id':distributor_id,
                };
                console.log(data);
                Fast.api.ajax({
                    url:'issuer/distributor/issue',
                    data:data
                }, function(data, ret){
                    console.log(data);
                    Fast.api.close();
                    //成功的回调
                    return true;
                }, function(data, ret){
                    // console.log(data);
                    //失败的回调
                    Toastr.error(ret.msg);
                    return false;
                });
            });
            
            $(document).on("change", ".card-type", function () {
                if(this.value == 0) {
                  document.getElementById('address').style.display="none"
                } else {
                  document.getElementById('address').style.display="inline-block"
                }
            });
            $(document).on("change", ".price", function () {
                if(this.value == 0) {
                  document.getElementById('put_price').style.display="inline-block"
                  document.getElementById('send_result').style.display="none"
                } else {
                  document.getElementById('put_price').style.display="none"
                  document.getElementById('send_result').style.display="inline-block"
                  addform.univalent = 0
                  addform.price = 0
                }
            });
            
            $(document).on("change", ".voucher", function () {
                if(this.value == 1 || this.value == 2) {
                  document.getElementById('voucher1').classList.remove('none')
                  document.getElementById('voucher2').classList.add('none')
                } else {
                  document.getElementById('voucher2').classList.remove('none')
                  document.getElementById('voucher1').classList.add('none')
                }
            });
            
            // var voucher = $("input[name=voucher]:checked").val();
            // console.log(voucher,'voucher');

            var addform = new Vue({
                el: "#add-form",
                data() {
                    return {
                        data: [],
                        options: [],
                        value: '',
                        searchKey: '',
                        price: 0,
                        num: 0,
                        univalent: 0
                    }
                },
                created() {
                    this.getRegion();
                },
                methods: {
                    handleChange() {
                        console.log(111, '');
                    },
                    //获取地区信息
                    getRegion() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'issuer/distributor/getProvinceCity',
                        }, function(data, ret) {
                            console.log(data.info,'data.info');
                            that.options = JSON.parse(data.info)
                            return false;
                        }, function(data, ret) {
                            //失败的回调
                            Toastr.error(ret.msg);
                            return false;
                        });
                    },
                    inputNum(e) {
                      this.num = document.getElementById('put_num').value
                      console.log(this.num,'num');
                      this.price = this.univalent * this.num
                    },
                    inputUnivalent(e) {
                      this.univalent = document.getElementById('put_price').value
                      console.log(this.univalent,'univalent');
                      this.price = this.univalent * this.num
                    }
                },
            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $(document).on('click', "input[name='row[ismenu]']", function () {
                    var name = $("input[name='row[name]']");
                    name.prop("placeholder", $(this).val() == 1 ? name.data("placeholder-menu") : name.data("placeholder-node"));
                });
                $("input[name='row[ismenu]']:checked").trigger("click");
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
